﻿using System;
using System.Windows.Controls;
using nRoute.ViewServices;
using nRoute.Samples.OfficerXcel.ViewServices;
using nRoute.Components;

namespace nRoute.Samples.OfficerXcel
{
    [MapViewService(typeof(IStatusViewService), Lifetime = ViewServiceLifetime.DiscoveredInstance)]
    public partial class Shell
        : UserControl, IStatusViewService
    {
        private const string DEFAULT_STATUS = "Ready";

        private readonly Object _statusLock = new Object();
        private DisposableToken _activeStatusToken;

        public Shell()
        {
            InitializeComponent();
        }

#region IStatusViewService Members

        public IDisposable UpdateStatus(string status)
        {
            // basic check
            if (string.IsNullOrEmpty(status)) throw new ArgumentNullException("status");

            // we use locks to ensure we don't override any token before disposing it
            lock (_statusLock)
            {
                // we dispose the old status
                if (_activeStatusToken != null && !_activeStatusToken.IsDisposed)
                    _activeStatusToken.Dispose();

                // update the status
                StatusText.Text = status;

                // and return a token
                _activeStatusToken = new DisposableToken(ClearStatus);
                return _activeStatusToken;
            }
        }

#endregion

#region Helpers

        void ClearStatus()
        {
            lock (_statusLock)
            {
                _activeStatusToken = null;
                StatusText.Text = DEFAULT_STATUS;
            }
        }

#endregion

    }
}
